package my.myorm.tool.jdbc;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2010-10-22
 * Time: 9:54:14
 * To change this template use File | Settings | File Templates.
 */
public class MySqlPageQueryer implements PageQueryer {
    public String getSuffixSqlForTotal(String sql) throws Exception {
        String lowercaseSql = sql.toLowerCase();
        int formIndex = lowercaseSql.indexOf(" from ");
        int orderbyIndex = lowercaseSql.indexOf(" order by ");
        int groupbyIndex = lowercaseSql.indexOf(" group by ");
        String suffixsql = "";
        if(orderbyIndex > 0) {
            suffixsql = sql.substring(formIndex, orderbyIndex);
        } else {
            suffixsql = sql.substring(formIndex);
        }
        if(groupbyIndex > 0 || lowercaseSql.indexOf(" union ") >= 0) {
            suffixsql = "from (" + (orderbyIndex > 0 ? sql.substring(0, orderbyIndex) : sql) + ") as a";
        }
        return suffixsql;
    }

    public String getSqlForPage(String sql, int start, int pagesize) throws Exception {
        int limitIndex = sql.indexOf(" limit ");
        if(limitIndex > 0) {
            sql = sql.substring(0, limitIndex);
        }
        return sql + " limit " + start + "," + pagesize;
    }
}
